<?php

namespace util;

use app\model\TemplateSubscribe;
use app\model\UserInfo;
use constant\RedisConstant;

class WeChatTool
{

    /**
     * coreAPI constructor.
     */
    private static function getConfig()
    {
        $config['appid'] = '';
        $config['app_secret'] = '';
        return [$config['appid'], $config['app_secret']];
    }

    /*****************************************小程序*************************************************/

    /**
     * 小程序授权登录,获取openid
     * @param string $code
     */
    public static function authLogin($code)
    {
        list($appid, $app_secret) = self::getConfig();
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $app_secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = httpGet($url);
        if (is_array($res) && isset($res['openid'])) {
            return [true, $res, ''];
        } else {
            return [false, [], "授权登录失败！"];
        }
    }

    /**
     * 获取手机号
     * @param $code
     * @return mixed
     */
    public static function getPhoneNumber($code)
    {
        $TOKEN = self::GetAccessToken();
        $URL = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $TOKEN;
        $data = array('code' => $code);
        $result = httpPost($URL, json_encode($data));
        if ($result['errcode'] == 0) {
            return $result['phone_info']['phoneNumber'] ?: '';
        }
        return '';
    }

    /**
     * 获取access_token
     * @return mixed
     */
    public static function GetAccessToken()
    {
        list($appid, $app_secret) = self::getConfig();
        $access_token = RedisTool::get_time('access_token', 'config');
        if ($access_token)
            return $access_token;
        else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$app_secret}";
            $res = httpGet($url);
            if (is_array($res)) {
                $access_token = $res['access_token'];
                $expires_in = $res['expires_in'];//凭证有效时间，单位秒，正常为7200
                RedisTool::set_time('access_token', $access_token, $expires_in - 1000, 'config');
                return $access_token;
            }
            return '';
        }
    }


    //生成指定长度的随机字符串
    public static function createNonceStr($length)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 上传临时素材
     * @param $imageUrl
     * @return mixed 返回素材id
     */
    public static function uploadMedia($imageUrl)
    {
        $TOKEN = self::GetAccessToken();
        $URL = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $TOKEN . '&type=image';
        $data = array('media' => '@' . $imageUrl);
        $result = httpPost($URL, json_encode($data));
        return $result['media_id'];
    }

    /**
     * 检查用户信息(文本)
     * @param $content string 文本内容
     * @param $openid string openid
     * @param int $type 1：资料 2：评论 3：论坛 4：社交日志
     * @return mixed
     */
    public static function msgSecCheck($content, $openid, $type = 1)
    {
        $TOKEN = self::GetAccessToken();
        $URL = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $TOKEN;
        $data['content'] = $content;
        $data['version'] = 2;
        $data['scene'] = $type;
        $data['openid'] = $openid;
        $result = httpPost($URL, json_encode($data));
        return @json_decode($result, true);
    }

    /**
     * 检查用户信息（图片，音频）
     * @tips 异步调用
     * @param $url string 图片、音频地址
     * @param $openid string openid
     * @param int $type 1：资料 2：评论 3：论坛 4：社交日志
     * @param int $media_type 1：音频 2：图片
     * @return mixed
     */
    public static function mediaCheckAsync($url, $openid, $type = 1, $media_type = 2)
    {
        $TOKEN = self::GetAccessToken();
        $URL = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $TOKEN;
        $data['media_url'] = $url;
        $data['media_type'] = $media_type;
        $data['version'] = 2;
        $data['scene'] = $type;
        $data['openid'] = $openid;
        $result = httpPost($URL, json_encode($data));
        return @json_decode($result, true);
    }
}